package com.budwk.app.sqfw.controllers.admin;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.ObjectUtil;
import com.budwk.app.oss.models.SysOss;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sqfw.constants.SqfwCloudBusinessConstants;
import com.budwk.app.sqfw.dto.SqfwServiceOrderUpdateDTO;
import com.budwk.app.sqfw.dto.SqfwServiceRecordUpdateDTO;
import com.budwk.app.sqfw.dto.TransferServiceRecordDTO;
import com.budwk.app.sqfw.models.Sqfw_cloudcallback;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_workorder;
import com.budwk.app.sqfw.services.*;
import com.budwk.app.sqfw.tencent.TCyysb;
import com.budwk.app.sqfw.vo.ServiceOrderOfUserVO;
import com.budwk.app.sqfw.vo.SqfwWorkOrderVO;
import com.budwk.app.sqfw.vo.UserServiceOrderVO;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysRoleService;
import com.budwk.app.sys.services.SysRoleUserService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.AudioToTextUtils;
import com.budwk.starter.common.exception.BaseException;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import com.budwk.app.sqfw.models.Sqfw_servicerecord;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import jodd.io.FileUtil;
//import org.apache.commons.compress.utils.Lists;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;
import org.nutz.lang.Strings;
import com.budwk.starter.common.openapi.annotation.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@IocBean
@At("/platform/sqfw/servicerecord")
@ApiDefinition(tag = "通讯服务记录")
@Slf4j
public class SqfwServicerecordController {
    @Inject
    private SqfwServicerecordService sqfwServicerecordService;

    @Inject
    private SqfwWorkorderService sqfwWorkorderService;

    @Inject
    private SysUserService sysUserService;

    @Inject
    private SysRoleUserService sysRoleUserService;

    @Inject
    private SysRoleService sysRoleService;

    @Inject
    private HuaweiOssService huaweiOssService;

    @Inject
    private PropertiesProxy propertiesProxy;

    @Inject
    private SysOssService sysOssService;

    @Inject
    private SqfwCloudcallbackService sqfwCloudcallbackService;

    private final ExecutorService executorService = Executors.newFixedThreadPool(50);

    private final String EOL = System.getProperty("line.separator");

    private Logger logger;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;
    @Inject
    Dao dao;


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询通讯服务记录")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_servicerecord.class
    )
    @ApiResponses(
            implementation = Sqfw_servicerecord.class
    )
    @SaCheckPermission("sqfw.servicerecord")
    @SLog(tag = "分页查询通讯服务记录")
    public Result<?> list(@Param("..") Sqfw_servicerecord bean, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy, @Param("workOrderFlag") Boolean workOrderFlag) {

        long startTime = System.currentTimeMillis();

        Cnd cnd = createListServiceRecordPermissionCnd(SecurityUtil.getUserId());
        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        } else {
            cnd.orderBy("createdat", "desc");
        }

        if (bean.getCustomer_name() != null && Strings.isNotBlank(bean.getCustomer_name().toString())) {
            cnd.and("customer_name", "like", "%" + bean.getCustomer_name() + "%");
        }

        if (bean.getFinishStatus() != null && Strings.isNotBlank(bean.getFinishStatus().toString())) {
            cnd.and("finish_status", "like", "%" + bean.getFinishStatus() + "%");
        }

        if (bean.getDuration() != null && Strings.isNotBlank(bean.getDuration().toString())) {
            cnd.and("duration", "like", "%" + bean.getDuration() + "%");
        }

        if (bean.getCustomer_phone() != null && Strings.isNotBlank(bean.getCustomer_phone().toString())) {
            cnd.and("customer_phone", "like", "%" + bean.getCustomer_phone() + "%");
        }

        if (bean.getCustomer_address() != null && Strings.isNotBlank(bean.getCustomer_address().toString())) {
            cnd.and("customer_address", "like", "%" + bean.getCustomer_address() + "%");
        }

        if (bean.getRecording_file() != null && Strings.isNotBlank(bean.getRecording_file().toString())) {
            cnd.and("recording_file", "like", "%" + bean.getRecording_file() + "%");
        }

        if (bean.getRecording_text() != null && Strings.isNotBlank(bean.getRecording_text().toString())) {
            cnd.and("recording_text", "like", "%" + bean.getRecording_text() + "%");
        }

        if (bean.getType() != null && Strings.isNotBlank(bean.getType().toString())) {
            cnd.and("type", "like", "%" + bean.getType() + "%");
        }

        if (bean.getConnect_time() != null && Strings.isNotBlank(bean.getConnect_time().toString())) {
            Instant instant = bean.getConnect_time().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startdateStr = localDateTime.format(fmt);
            String enddateStr = localDateTime.plusDays(1).format(fmt);

            cnd.and("connect_time", "between", new Object[]{startdateStr, enddateStr});
        }

        if (bean.getEnd_time() != null && Strings.isNotBlank(bean.getEnd_time().toString())) {
            Instant instant = bean.getEnd_time().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startdateStr = localDateTime.format(fmt);
            String enddateStr = localDateTime.plusDays(1).format(fmt);

            cnd.and("connect_time", "between", new Object[]{startdateStr, enddateStr});
        }

        if (bean.getCustomer_need() != null && Strings.isNotBlank(bean.getCustomer_need().toString())) {
            cnd.and("customer_need", "like", "%" + bean.getCustomer_need() + "%");
        }

        if (bean.getService_name() != null && Strings.isNotBlank(bean.getService_name().toString())) {
            cnd.and("service_name", "like", "%" + bean.getService_name() + "%");
        }

        if (bean.getService_phone() != null && Strings.isNotBlank(bean.getService_phone().toString())) {
            cnd.and("service_phone", "like", "%" + bean.getService_phone() + "%");
        }

        if (bean.getReceive_time() != null && Strings.isNotBlank(bean.getReceive_time().toString())) {
            Instant instant = bean.getReceive_time().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startdateStr = localDateTime.format(fmt);
            String enddateStr = localDateTime.plusDays(1).format(fmt);

            cnd.and("receive_time", "between", new Object[]{startdateStr, enddateStr});
        }

        if (bean.getFinish_time() != null && Strings.isNotBlank(bean.getFinish_time().toString())) {
            Instant instant = bean.getFinish_time().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startdateStr = localDateTime.format(fmt);
            String enddateStr = localDateTime.plusDays(1).format(fmt);

            cnd.and("finish_time", "between", new Object[]{startdateStr, enddateStr});
        }

        if (bean.getCreatedAt() != null && Strings.isNotBlank(bean.getCreatedAt().toString())) {
            Long endDate = bean.getCreatedAt() + 86400000;
            cnd.and("createdat", "between", new Object[]{bean.getCreatedAt(), endDate});
        }

        if (bean.getHandle_result() != null && Strings.isNotBlank(bean.getHandle_result().toString())) {
            cnd.and("handle_result", "=", "%" + bean.getHandle_result() + "%");
        }

        if (bean.getHandle_detail() != null && Strings.isNotBlank(bean.getHandle_detail().toString())) {
            cnd.and("handle_detail", "like", "%" + bean.getHandle_detail() + "%");
        }

        if (bean.getHandle_detail() != null && Strings.isNotBlank(bean.getHandle_detail().toString())) {
            cnd.and("handle_detail", "like", "%" + bean.getHandle_detail() + "%");
        }

        if (bean.getCopyName() != null && Strings.isNotBlank(bean.getCopyName().toString())) {
            cnd.and("copy_name", "like", "%" + bean.getCopyName() + "%");
        }

        if (bean.getCopyPhone() != null && Strings.isNotBlank(bean.getCopyPhone().toString())) {
            cnd.and("copy_phone", "like", "%" + bean.getCopyPhone() + "%");
        }

        if (bean.getCompanyName() != null && Strings.isNotBlank(bean.getCompanyName().toString())) {
            cnd.and("company_name", "like", "%" + bean.getCompanyName() + "%");
        }

        if (bean.getCreatedBy() != null && Strings.isNotBlank(bean.getCreatedBy())) {
            cnd.and("createdby", "=", bean.getCreatedBy());
        }

        cnd.and("delflag", "=", false);
        SqlExpressionGroup e1 = Cnd.exps(Sqfw_servicerecord::getHzqd,"<>","祥云小助");
        SqlExpressionGroup e2 = Cnd.exps(Sqfw_servicerecord::getHzqd,"is",null);
        cnd.and(e1.or(e2));
        Pagination pagination = sqfwServicerecordService.listPage(pageNo, pageSize, cnd);

        List<Sqfw_servicerecord> list = pagination.getList(Sqfw_servicerecord.class);

        // 如果需要查看相应的工单信息
        if (workOrderFlag != null && workOrderFlag) {
            CountDownLatch countDownLatch = new CountDownLatch(list.size());

            ConcurrentHashMap<String, UserServiceOrderVO> resultServiceOrderMap = new ConcurrentHashMap<>();
            for (Sqfw_servicerecord serviceRecord : list) {
                executorService.execute(() -> {
                    try {
                        UserServiceOrderVO resultVO = new UserServiceOrderVO();
                        BeanUtil.copyProperties(serviceRecord, resultVO);

                        // 根据sqfw_id 和 from_userid 查询相应的工单信息
                        List<Sqfw_workorder> workOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                                .and("from_user_id", "=", serviceRecord.getCreatedBy()));
                        resultVO.setUserWorkOrderList(sqfwWorkorderService.getVO(workOrderList));

                        // 根据sqfw_id 和 user_id 查询该语音记录所对应的工单信息
                        List<Sqfw_workorder> curServiceOrderWorkOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                                .and("user_id", "=", serviceRecord.getCreatedBy()));
                        List<SqfwWorkOrderVO> curUserVOList = sqfwWorkorderService.getVO(curServiceOrderWorkOrderList);
                        if (curUserVOList.size() > 0) resultVO.setUserWorkOrder(curUserVOList.get(0));

                        List<Sqfw_workorder> workOrderOfRecordList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                                .and("from_user_id", "is not", null)
                                .and("delflag", "=", false));
                        int workOrderCompleteCount = 0;
                        int workOrderNotCompleteCount = 0;
                        for (Sqfw_workorder workOrderOfRecord : workOrderOfRecordList) {
                            String wk_status = workOrderOfRecord.getWk_status();
                            if (StringUtils.isNotBlank(wk_status) && wk_status.equals("complete"))
                                workOrderCompleteCount++;
                            else workOrderNotCompleteCount++;
                        }
                        String completeMsg = StrFormatter.format("完成{}人，未完成{}人", workOrderCompleteCount, workOrderNotCompleteCount);
                        resultVO.setHandle_result(completeMsg);


                        resultServiceOrderMap.put(resultVO.getId(), resultVO);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        countDownLatch.countDown();
                    }
                });
            }

            try {
                countDownLatch.await();
            } catch (Exception ignored) {
            }

            List<UserServiceOrderVO> resultList = Lists.newArrayList();
            for (Sqfw_servicerecord sqfw_servicerecord : list) {
                resultList.add(resultServiceOrderMap.get(sqfw_servicerecord.getId()));
            }
            pagination.setList(resultList);
        }

        long endTime = System.currentTimeMillis();
        System.out.println("---------------" + (endTime - startTime));
        return Result.data(pagination);

    }


    /**
     * 任务记录管理列表查询（用于后台管理系统）
     * Add by LJT 2023-10-08
     */
    @At("/listForBM")
    @Ok("json")
    @POST
    @ApiOperation(name = "任务记录管理列表分页查询")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_servicerecord.class
    )
    @ApiResponses(
            implementation = Sqfw_servicerecord.class
    )
    @SLog(tag = "任务记录管理列表分页查询")
    //@SaCheckPermission("sqfw.servicerecord")
    public Result<?> listForBM(@Param("..") Sqfw_servicerecord bean, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy, @Param("workOrderFlag") Boolean workOrderFlag) throws ParseException {

        long startTime = System.currentTimeMillis();

        Cnd cnd = createListServiceRecordPermissionCnd(SecurityUtil.getUserId());
        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        } else {
            cnd.orderBy("createdat", "desc");
        }

        if (bean.getCommunity() != null && Strings.isNotBlank(bean.getCommunity().toString())) {
            cnd.and("community", "like", "%" + bean.getCommunity() + "%");
        }

        if (bean.getCustomer_name() != null && Strings.isNotBlank(bean.getCustomer_name().toString())) {
            cnd.and("customer_name", "like", "%" + bean.getCustomer_name() + "%");
        }

        if (bean.getFinishStatus() != null && Strings.isNotBlank(bean.getFinishStatus().toString())) {
            cnd.and("finish_status", "like", "%" + bean.getFinishStatus() + "%");
        }

        if (bean.getDuration() != null && Strings.isNotBlank(bean.getDuration().toString())) {
            cnd.and("duration", "like", "%" + bean.getDuration() + "%");
        }

        if (bean.getCustomer_phone() != null && Strings.isNotBlank(bean.getCustomer_phone().toString())) {
            cnd.and("customer_phone", "like", "%" + bean.getCustomer_phone() + "%");
        }

        if (bean.getCustomer_address() != null && Strings.isNotBlank(bean.getCustomer_address().toString())) {
            cnd.and("customer_address", "like", "%" + bean.getCustomer_address() + "%");
        }

        if (bean.getRecording_file() != null && Strings.isNotBlank(bean.getRecording_file().toString())) {
            cnd.and("recording_file", "like", "%" + bean.getRecording_file() + "%");
        }

        if (bean.getRecording_text() != null && Strings.isNotBlank(bean.getRecording_text().toString())) {
            cnd.and("recording_text", "like", "%" + bean.getRecording_text() + "%");
        }

        if (bean.getType() != null && Strings.isNotBlank(bean.getType().toString())) {
            cnd.and("type", "like", "%" + bean.getType() + "%");
        }

        if (bean.getCustomer_need() != null && Strings.isNotBlank(bean.getCustomer_need().toString())) {
            cnd.and("customer_need", "like", "%" + bean.getCustomer_need() + "%");
        }

        if (bean.getService_name() != null && Strings.isNotBlank(bean.getService_name().toString())) {
            cnd.and("service_name", "like", "%" + bean.getService_name() + "%");
        }

        if (bean.getService_phone() != null && Strings.isNotBlank(bean.getService_phone().toString())) {
            cnd.and("service_phone", "like", "%" + bean.getService_phone() + "%");
        }

        if (bean.getQueryTime() != null && Strings.isNotBlank(bean.getQueryTime())) {
            String time[] = bean.getQueryTime().split(",");
            cnd.and("createdat", "between", new Object[]{time[0], time[1]});
        }

        if (bean.getHandle_result() != null && Strings.isNotBlank(bean.getHandle_result().toString())) {
            cnd.and("handle_result", "=", "%" + bean.getHandle_result() + "%");
        }

        if (bean.getHandle_detail() != null && Strings.isNotBlank(bean.getHandle_detail().toString())) {
            cnd.and("handle_detail", "like", "%" + bean.getHandle_detail() + "%");
        }

        if (bean.getHandle_detail() != null && Strings.isNotBlank(bean.getHandle_detail().toString())) {
            cnd.and("handle_detail", "like", "%" + bean.getHandle_detail() + "%");
        }

        if (bean.getCopyName() != null && Strings.isNotBlank(bean.getCopyName().toString())) {
            cnd.and("copy_name", "like", "%" + bean.getCopyName() + "%");
        }

        if (bean.getCopyPhone() != null && Strings.isNotBlank(bean.getCopyPhone().toString())) {
            cnd.and("copy_phone", "like", "%" + bean.getCopyPhone() + "%");
        }

        if (bean.getCompanyName() != null && Strings.isNotBlank(bean.getCompanyName().toString())) {
            cnd.and("company_name", "like", "%" + bean.getCompanyName() + "%");
        }

        if (bean.getCreatedBy() != null && Strings.isNotBlank(bean.getCreatedBy())) {
            cnd.and("createdby", "=", bean.getCreatedBy());
        }

        cnd.and("delflag", "=", false);

        Pagination pagination = sqfwServicerecordService.listPage(pageNo, pageSize, cnd);

        List<Sqfw_servicerecord> listOld = pagination.getList(Sqfw_servicerecord.class);

        List<Sqfw_servicerecord> list = new ArrayList<Sqfw_servicerecord>();
        for (Sqfw_servicerecord sqfw_servicerecord : listOld) {
            if (StringUtils.isNotBlank(sqfw_servicerecord.getUser_id())) {
                Sys_user sysUser = sysUserService.fetch(sqfw_servicerecord.getUser_id());
                if (StringUtils.isNotBlank(bean.getCommunity())) {
                    if (StringUtils.isNotBlank(sysUser.getCommunity()) && sysUser.getCommunity().contains(bean.getCommunity())) {
                        sqfw_servicerecord.setCommunity(sysUser.getCommunity());
                        list.add(sqfw_servicerecord);
                    }
                } else if (StringUtils.isNotBlank(sysUser.getCommunity())) {
                    sqfw_servicerecord.setCommunity(sysUser.getCommunity());
                    list.add(sqfw_servicerecord);
                }
            }
        }

        // 如果需要查看相应的工单信息
        if (workOrderFlag != null && workOrderFlag) {
            CountDownLatch countDownLatch = new CountDownLatch(list.size());

            ConcurrentHashMap<String, UserServiceOrderVO> resultServiceOrderMap = new ConcurrentHashMap<>();
            for (Sqfw_servicerecord serviceRecord : list) {
                executorService.execute(() -> {
                    try {
                        UserServiceOrderVO resultVO = new UserServiceOrderVO();
                        BeanUtil.copyProperties(serviceRecord, resultVO);

                        // 根据sqfw_id 和 from_userid 查询相应的工单信息
                        List<Sqfw_workorder> workOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                                .and("from_user_id", "=", serviceRecord.getCreatedBy()));
                        resultVO.setUserWorkOrderList(sqfwWorkorderService.getVO(workOrderList));

                        // 根据sqfw_id 和 user_id 查询该语音记录所对应的工单信息
                        List<Sqfw_workorder> curServiceOrderWorkOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                                .and("user_id", "=", serviceRecord.getCreatedBy()));
                        List<SqfwWorkOrderVO> curUserVOList = sqfwWorkorderService.getVO(curServiceOrderWorkOrderList);
                        if (curUserVOList.size() > 0) resultVO.setUserWorkOrder(curUserVOList.get(0));

                        List<Sqfw_workorder> workOrderOfRecordList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                                .and("from_user_id", "is not", null)
                                .and("delflag", "=", false));
                        int workOrderCompleteCount = 0;
                        int workOrderNotCompleteCount = 0;
                        for (Sqfw_workorder workOrderOfRecord : workOrderOfRecordList) {
                            String wk_status = workOrderOfRecord.getWk_status();
                            if (StringUtils.isNotBlank(wk_status) && wk_status.equals("complete"))
                                workOrderCompleteCount++;
                            else workOrderNotCompleteCount++;
                        }
                        String completeMsg = StrFormatter.format("完成{}人，未完成{}人", workOrderCompleteCount, workOrderNotCompleteCount);
                        resultVO.setHandle_result(completeMsg);


                        resultServiceOrderMap.put(resultVO.getId(), resultVO);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        countDownLatch.countDown();
                    }
                });
            }

            try {
                countDownLatch.await();
            } catch (Exception ignored) {
            }

            List<UserServiceOrderVO> resultList = Lists.newArrayList();
            for (Sqfw_servicerecord sqfw_servicerecord : list) {
                resultList.add(resultServiceOrderMap.get(sqfw_servicerecord.getId()));
            }
            pagination.setTotalCount(resultList.size());
            pagination.setList(resultList);
        }

        long endTime = System.currentTimeMillis();
        System.out.println("---------------" + (endTime - startTime));
        return Result.data(pagination);

    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "新增通讯服务记录")
    @ApiFormParams(
            implementation = Sqfw_servicerecord.class
    )
    @ApiResponses
    @SLog(tag = "新增通讯服务记录", value = "${args[0].id}")
    @SaCheckPermission("sqfw.servicerecord.create")
    public Result<?> create(@Param("..") SqfwServiceRecordUpdateDTO sqfwServicerecord, HttpServletRequest req) {
        String userId = SecurityUtil.getUserId();
        Sys_user sysUser = sysUserService.fetch(userId);
        if (sysUser == null) return Result.error("当前登录用户错误,请重新登录");

        // wzy 2023-11-22 从后端查出用户数据进行赋值地级市5级数据
        sqfwServicerecord.setProvince(sysUser.getProvince());
        sqfwServicerecord.setCity(sysUser.getCity());
        sqfwServicerecord.setDistrict(sysUser.getDistrict());
        sqfwServicerecord.setCounty(sysUser.getCounty());
        sqfwServicerecord.setCommunity(sysUser.getCommunity());
        sqfwServicerecord.setCreatedBy(userId);
        String getPhone = sqfwServicerecord.getService_phone();
        sqfwServicerecord.setDelFlag(false);

        // 赋值关于语音时常相关属性
        if (!StringUtils.isNotBlank(sqfwServicerecord.getService_phone()) && sqfwServicerecord.getDuration() != null) {
            long audioDuration = sqfwServicerecord.getDuration() / 1000;
            sqfwServicerecord.setDuration(audioDuration);
            Date endTime = new Date(sqfwServicerecord.getConnect_time().getTime() + audioDuration);
            sqfwServicerecord.setEnd_time(endTime);
        }
        sqfwServicerecord.setRecording_text(sqfwServicerecord.getRecording_text());
        sqfwServicerecord.setService_phone(null);
        sqfwServicerecord.setService_name(null);
        sqfwServicerecord.setFinishStatus("new");

        // 处理语音转文字相关事情
        Sqfw_cloudcallback cloudCallBack = handleVideoTransTextAtServiceRecordCreate(sqfwServicerecord);

        Sqfw_servicerecord newServiceOrder = sqfwServicerecordService.insert(sqfwServicerecord);

        if (cloudCallBack != null) {
            cloudCallBack.setBusinessId(newServiceOrder.getId());
            sqfwCloudcallbackService.insert(cloudCallBack);
        }

        Result<String> result = Result.NEW();
        result.addData(sqfwServicerecord.getId());

        // 新增语音通话需要生成一个工单
        Sqfw_workorder workOrder = new Sqfw_workorder();
        workOrder.setSqfw_id(newServiceOrder.getId());
        workOrder.setUser_name(sysUser.getUsername());
        workOrder.setWk_grade("0");
        workOrder.setWk_priority("take_time_complete");
        workOrder.setUser_id(newServiceOrder.getCreatedBy());
        workOrder.setCreateDate(new Date());
        workOrder.setUpdatedAt(new Date());
        workOrder.setCreatedBy(newServiceOrder.getCreatedBy());
        // wzy 2023-5-25 服务记录生成工单的时候不主动完成对应工单
        workOrder.setWk_status("new");
        // workOrder.setComplete_time(new Date());
        workOrder.setDelflag(false);
        workOrder.setServiceType(sqfwServicerecord.getType());
        sqfwWorkorderService.insert(workOrder);

        if (StringUtils.isNotBlank(getPhone)) {
            List<String> strings = new ArrayList<>();
            TransferServiceRecordDTO dto = new TransferServiceRecordDTO();
            dto.setServiceRecordId(newServiceOrder.getId());
            List<String> list = Lists.newArrayList(getPhone.split(","));
            for (String str : list) {
                Sys_user querySysUser = sysUserService.getUserByLoginname(str);
                strings.add(querySysUser.getId());
            }
            dto.setToSysUserIdList(strings);
            sqfwWorkorderService.transferServiceRecordNew(dto);
        }

        return result;
    }

    /**
     * 语音转文字使用的方法
     *
     * @param serviceRecord 服务记录
     */
    private Sqfw_cloudcallback handleVideoTransTextAtServiceRecordCreate(SqfwServiceRecordUpdateDTO serviceRecord) {
        if (StringUtils.isNotBlank(serviceRecord.getRecording_file())
                && !serviceRecord.getApp_type().equals("7")
                && !serviceRecord.getApp_type().equals("8")) {

            Boolean cloudTransFlag = serviceRecord.getCloudTransFlag();
            cloudTransFlag = cloudTransFlag == null;
            if (cloudTransFlag) {
                // 这里会进行语音识别 分为两个分支一个是调用腾讯的语音识别，另外一个是手机本地已经识别完成，然后直接使用
                String url = huaweiOssService.getPwdPath(serviceRecord.getRecording_file());

                String serviceIp = propertiesProxy.get("jarService.ip");
                String port = propertiesProxy.get("server.port");
                String callback = StrFormatter.format("http://{}:{}/platform/sqfw/cloudcallback/callback", serviceIp, port);
                Long taskId = TCyysb.Send(url, callback);

                if (taskId != null && taskId > 0L) {
                    serviceRecord.setTaskId(taskId.toString());
                }

                return null;
            } else {
                String localAudioTransText = serviceRecord.getLocalAudioTransText();
                String localAudioTransOriText = serviceRecord.getLocalAudioTransOriText();
                serviceRecord.setRecording_text(serviceRecord.getLocalAudioTransText());

                Sqfw_cloudcallback cloudCallBack = new Sqfw_cloudcallback();
                cloudCallBack.setAudioUrl(serviceRecord.getRecording_file());
                cloudCallBack.setText(localAudioTransText);  // 这个字段存已经通过系统替换过的文本
                cloudCallBack.setResultDetail(localAudioTransOriText);
                cloudCallBack.setBusinessId(serviceRecord.getId());
                cloudCallBack.setBusinessType(SqfwCloudBusinessConstants.SERVICE_RECORD);
                cloudCallBack.setCreatedAt(new Date().getTime());
                cloudCallBack.setUpdatedAt(new Date().getTime());
                cloudCallBack.setDelFlag(false);
                cloudCallBack.setTransChannel(SqfwCloudBusinessConstants.TRANS_CHANNEL_DFSJ);
                return cloudCallBack;
            }
        }

        return null;
    }

    @At("/updateTransmit")
    @Ok("json")
    @POST
    @ApiOperation(name = "修改转发")
    @ApiFormParams(
            implementation = Sqfw_servicerecord.class
    )
    @ApiResponses
    @SLog(tag = "修改转发", value = "${id}")
    // @SaCheckPermission("sqfw.servicerecord.update")
    public Result<?> updateTransmit(@Param("id") String id, @Param("service_phone") String service_phone, @Param("wk_priority") String wk_priority) {
        List<String> strings = new ArrayList<>();
        TransferServiceRecordDTO dto = new TransferServiceRecordDTO();
        dto.setServiceRecordId(id);
        List<String> list = Lists.newArrayList(service_phone.split(","));
        for (String str : list) {
            Sys_user sysUser = sysUserService.getUserByLoginname(str);
            strings.add(sysUser.getId());
        }
        dto.setToSysUserIdList(strings);
        dto.setWorkOrderWkPriority(wk_priority);
        sqfwWorkorderService.transferServiceRecordNew(dto);

        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "修改通讯服务记录")
    @ApiFormParams(
            implementation = Sqfw_servicerecord.class
    )
    @ApiResponses
    @SLog(tag = "修改通讯服务记录", value = "${args[0]}")
    // @SaCheckPermission("sqfw.servicerecord.update")
    public Result<?> update(@Param("..") SqfwServiceOrderUpdateDTO sqfwServicerecord, HttpServletRequest req) {

        String finishStatus = sqfwServicerecord.getFinishStatus();
        if (StringUtils.isNotBlank(finishStatus) && finishStatus.equals("complete")) {
            String sqfwServicerecordId = sqfwServicerecord.getId();
            Sqfw_servicerecord existServiceOrder = sqfwServicerecordService.fetch(sqfwServicerecordId);
            if (StringUtils.isBlank(existServiceOrder.getFinishStatus()) || !existServiceOrder.getFinishStatus().equals("complete")) {
                sqfwServicerecord.setFinish_time(new Date());
            }
        }
        sqfwServicerecord.setUpdatedBy(SecurityUtil.getUserId());
        //20210110修改任务状态  删除对应任务接收人的任务状态  //任务完成可以取消
        String sqfwId=sqfwServicerecord.getId();
        if (StringUtils.isNotBlank(finishStatus) && finishStatus.equals("complete")&&StringUtils.isNotBlank(sqfwId)) {
            List<Sqfw_workorder> workorderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", sqfwId).and("delflag", "=", false));
            for (int i = 0; i < workorderList.size(); i++) {
                Sqfw_workorder workorder  =workorderList.get(i);
                if(!workorder.getWk_status().equals("complete"))
                {
                    workorder.setWk_status("complete");
                    workorder.setFlowStartTime(new Date());
                    workorder.setComplete_time(new Date());
                    sqfwWorkorderService.update(workorder);
                    Sqfw_completeflow flow= new Sqfw_completeflow();
                    flow.setSqfwId(sqfwId);
                    flow.setWorkerId(workorder.getId());
                    flow.setFileType("工作总结");
                    flow.setUserId(SecurityUtil.getUserId());
                    flow.setUserName(sqfwServicerecord.getCustomer_name());
                    flow.setPhone(sqfwServicerecord.getCustomer_phone());
                    flow.setText("本任务已被发布人完结");
                    flow.setTitle("分享了工作总结");
                    sqfwCompleteflowService.insert(flow);
                }

            }

        }


        sqfwServicerecordService.updateIgnoreNull(sqfwServicerecord);
        return Result.success();
    }

    @At("/get")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取通讯服务记录")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SaCheckPermission("sqfw.servicerecord")
    @SLog(tag = "根据id获取通讯服务记录,id:{$id}")
    public Result<?> getData(@Param("id") String id, HttpServletRequest req) {
        if (StringUtils.isBlank(id)) return Result.error("id不能为空");
        List<String> idList = new ArrayList<>();
        idList.add(id);
        List<UserServiceOrderVO> list = sqfwServicerecordService.listByServiceOrderIdList(idList);
        Sqfw_servicerecord sqfwServiceRecord = list.get(0);

        // 需要把所有时间去掉
        String newContent = AudioToTextUtils.replaceMsgContentNotPrefix(sqfwServiceRecord.getRecording_text());
        sqfwServiceRecord.setRecording_text(newContent);

        String serviceRecordId = sqfwServiceRecord.getId();
        String createdBy = sqfwServiceRecord.getCreatedBy();
        List<Sqfw_workorder> workOrderList = sqfwWorkorderService.queryBySqfwIdAndFromUserId(serviceRecordId, createdBy);
        Set<String> userIdSet = workOrderList.stream().map(Sqfw_workorder::getUser_id).collect(Collectors.toSet());
        List<Sys_user> userList = sysUserService.getUserByIds(userIdSet);

        List<String> userNameList = new ArrayList<>();
        List<String> userPhoneList = new ArrayList<>();
        for (Sys_user sys_user : userList) {
            userNameList.add(sys_user.getUsername());
            userPhoneList.add(sys_user.getMobile());
        }

        if (userNameList.size() > 0) sqfwServiceRecord.setService_name(Joiner.on(",").join(userNameList));
        if (userPhoneList.size() > 0) sqfwServiceRecord.setService_phone(Joiner.on(",").join(userPhoneList));


        return Result.success(sqfwServiceRecord);
    }

    @At("/delete")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除通讯服务记录")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SLog(tag = "删除通讯服务记录", value = "${args[0]}")
    @SaCheckPermission("sqfw.servicerecord.delete")
    public Result<?> delete(@Param("id") String id, HttpServletRequest req) {
        Sqfw_servicerecord sqfwServicerecord = sqfwServicerecordService.fetch(id);
        if (sqfwServicerecord == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        sqfwServicerecordService.delete(id);
        req.setAttribute("_slog_msg", sqfwServicerecord.getId());
        return Result.success();
    }


    /**
     * 将word中某些标签替换成指定的值，并生成一个新的word文档。
     *
     * @throws IOException
     */
    @At("/insertAndOutFile")
    @Ok("json")
    @POST
    @ApiOperation(name = "word插入数据")
    @ApiFormParams()
    @SLog(tag = "word插入数据", value = "${args[0]},${args[1]},${args[2]}")
    @SaCheckPermission("sqfw.servicerecord.insertAndOutFile")
    public Result insertAndOutFile2(@Param("type") String type, @Param("startTime") String startTime, @Param("endTime") String endTime) {
        Result result = Result.NEW();
        Map<String, String> map = new HashMap<>();
        String pdf = "";
        String templateFile = propertiesProxy.get("cusconfig.report.reportPath") + "/file/金元小助播报模板.docx";


        String uploadresult = "";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = simpleDateFormat.format(new Date());
        if (type.equals("日报")) {
            map.put("type", "-" + type);
            File file = new File(templateFile);
            pdf = propertiesProxy.get("cusconfig.report.reportPath") + "/file/pdf/" + date + file.getName().replace("模板.docx", "") + type + ".pdf";
        }

        if (type.equals("周报")) {
            map.put("type", "-" + type);
            map.put("今日", "本周");
            File file = new File(templateFile);
            pdf = "/data/shequ/file/pdf/" + date + file.getName().replace("模板.docx", "") + type + ".pdf";
        }

        if (type.equals("月报")) {
            map.put("type", "-" + type);
            map.put("今日", "本月");
            File file = new File(templateFile);
            pdf = propertiesProxy.get("cusconfig.report.reportPath") + "/file/pdf/" + date + file.getName().replace("模板.docx", "") + type + ".pdf";
        }

        if (type.equals("")) {
            map.put("type", type);
            map.put("今日", "");
            File file = new File(templateFile);
            pdf = propertiesProxy.get("cusconfig.report.reportPath") + "/file/pdf/" + date + file.getName().replace("模板.docx", "") + type + ".pdf";
        }
        // 模板文件
        String filename = UUID.randomUUID().toString();
        String outPath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/word/" + filename + ".docx";
        try {
            String templateFilePath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/金元小助播报模板.docx";
            InputStream is1 = new FileInputStream(templateFilePath);
            InputStream is2 = new FileInputStream(templateFilePath);
            // 用来替换变量
            XWPFDocument hdt = new XWPFDocument(is1);
            // 用来输出原格式
            XWPFDocument hdt1 = new XWPFDocument(is2);

            //查询今日通话数量
            Cnd connectNumCnd = Cnd.NEW();
            connectNumCnd.and("customer_name", "=", SecurityUtil.getUserUsername());
            connectNumCnd.and("connect_time", "between", new Object[]{startTime, endTime});
            int connectNum = sqfwServicerecordService.count(connectNumCnd);

            map.put("name", SecurityUtil.getUserUsername());
            map.put("time", startTime + "——" + endTime);
            map.put("callnumber", String.valueOf(connectNum));

            //查询今日完成条数
            DecimalFormat df = new DecimalFormat("#.00");

            Cnd finishNumCnd = Cnd.NEW();
            finishNumCnd.and("customer_name", "=", SecurityUtil.getUserUsername());
            finishNumCnd.and("handle_result", "=", "完成");
            finishNumCnd.and("connect_time", "between", new Object[]{startTime, endTime});
            List<Sqfw_servicerecord> finishNum = sqfwServicerecordService.query(finishNumCnd);
            map.put("finishnumber", String.valueOf(finishNum.size()));
            if (connectNum == 0) {
                map.put("percentage", "0");
            } else {
                double percent = ((double) finishNum.size() / (double) connectNum) * 100;
                map.put("percentage", df.format(percent) + "%");
            }

            //计算平均完成时长
            double timeall = 0L;
            for (int i = 0; i < finishNum.size(); i++) {
                Long timelag = finishNum.get(i).getFinish_time().getTime() - finishNum.get(i).getReceive_time().getTime();
                double hour = timelag / 1000 * 0.0002777;
                timeall += hour;
            }
            if (finishNum.size() == 0) {
                map.put("avg", 0 + "小时");
            } else {
                map.put("avg", df.format(timeall / finishNum.size()) + "小时");
            }

            // TestPoi cc = new TestPoi();
            // 替换变量
            replaceText(hdt, map);
            // 替换成原格式
            setStyle(hdt1, hdt);

            // 输出文件
            OutputStream os = new FileOutputStream(outPath);
            hdt.write(os);
            hdt.close();
            hdt1.close();

            Word2PdfJacobUtil2(outPath, pdf);

            SysOss uploadOSS = sysOssService.upload(FileUtil.file(pdf));
            uploadresult = uploadOSS.getUrl();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        result.addData(uploadresult);
        return result;
    }


    public static void Word2PdfJacobUtil2(String inPath, String outPath) throws IOException {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            fileInputStream = new FileInputStream(inPath);
            XWPFDocument xwpfDocument = new XWPFDocument(fileInputStream);
            PdfOptions pdfOptions = PdfOptions.create();
            fileOutputStream = new FileOutputStream(outPath);
            PdfConverter.getInstance().convert(xwpfDocument, fileOutputStream, pdfOptions);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != fileInputStream) {
                    fileInputStream.close();
                }
                if (null != fileOutputStream) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void Word2PdfJacobUtil(String inPath, String outPath) throws IOException {

        InputStream docxInputStream = null;
        OutputStream outputStream = null;
        try {
            // 原word地址
            docxInputStream = new FileInputStream(inPath);
            // 转换后pdf生成地址
            outputStream = new FileOutputStream(outPath);
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream)
                    .as(DocumentType.DOCX)
                    .to(outputStream)
                    .as(DocumentType.PDF).execute();
            // 关闭
            converter.shutDown();
            // 关闭
            outputStream.close();
            // 关闭
            docxInputStream.close();
        } catch (Exception e) {
            System.out.println("[documents4J] word转pdf失败:" + e.toString());
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            if (docxInputStream != null) {
                docxInputStream.close();
            }
        }


    }


    /**
     * 替换文档中的参数（word）
     *
     * @param doc
     * @param params
     */
    private static void replaceText(XWPFDocument doc, Map<String, String> params) {
        Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
        XWPFParagraph para;
        while (iterator.hasNext()) {
            para = iterator.next();
            replaceInPara(para, params);
        }
    }

    /**
     * 替换段落中的参数（word）
     *
     * @param para
     * @param params
     */
    private static void replaceInPara(XWPFParagraph para, Map<String, String> params) {
        List<XWPFRun> runs = para.getRuns();
        for (int i = 0; i < runs.size(); i++) {
            XWPFRun run = runs.get(i);
            String runText = run.toString();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (runText.contains(entry.getKey())) {
                    para.removeRun(i);
                    // 重新插入run里内容格式可能与原来模板的格式不一致
                    para.insertNewRun(i).setText(runText.replace(entry.getKey(), entry.getValue()));
                }
            }
        }
    }

    /**
     * 处理文档替换内容的格式问题（word）
     *
     * @param tempDoc
     * @param doc
     */
    private static void setStyle(XWPFDocument tempDoc, XWPFDocument doc) {
        Iterator<XWPFParagraph> iterator = tempDoc.getParagraphsIterator();
        Iterator<XWPFParagraph> iterator2 = doc.getParagraphsIterator();
        XWPFParagraph para;
        XWPFParagraph para2;
        while (iterator.hasNext() && iterator2.hasNext()) {
            para = iterator.next();
            para2 = iterator2.next();
            setStyleInPara(para, para2);
        }
    }

    /**
     * 处理段落替换内容的格式问题（word）
     *
     * @param para
     * @param para2
     */
    private static void setStyleInPara(XWPFParagraph para, XWPFParagraph para2) {
        List<XWPFRun> runs = para.getRuns();
        List<XWPFRun> runs2 = para2.getRuns();
        for (int i = 0; i < runs.size(); i++) {
            XWPFRun run = runs.get(i);
            XWPFRun run2 = runs2.get(i);
            run2.getCTR().setRPr(run.getCTR().getRPr());
        }
    }

    @At("/listByServiceOrderIdList")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据serviceOrderId查询数据")
    @ApiFormParams(implementation = List.class)
    @ApiResponses
    @SLog(tag = "根据服务记录id查询数据")
    public Result<List<UserServiceOrderVO>> listByServiceOrderIdList(@Param("serviceOrderIdList") List<String> serviceOrderIdList) {
        List<UserServiceOrderVO> resultList = sqfwServicerecordService.listByServiceOrderIdList(serviceOrderIdList);
        return Result.success(resultList);
    }

    @At("/getServiceOrderDetail")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取通讯服务记录")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "serviceOrderId", description = "唯一标识", required = true, check = true),
                    @ApiFormParam(name = "userId", description = "用户id", required = true, check = true),
            }
    )
    @SLog(tag = "根据服务记录id获取通讯服务记录", value = "${args[0]},${args[1]},${args[2]}")
    public Result<UserServiceOrderVO> getServiceOrderDetail(@Param("serviceOrderId") String serviceOrderId, @Param("userId") String userId, @Param("recordType") String recordType) {
        if (StringUtils.isBlank(serviceOrderId)) return Result.error("id不能为空");
        // 使用id查serviceOder
        Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(serviceOrderId);

        if (serviceRecord == null) return Result.error("语音服务记录为空");

        // wzy 2023-5-19 需要对通话记录中的内容
        if (StringUtils.isNotBlank(serviceRecord.getRecording_text())) {
            serviceRecord.setRecording_text(AudioToTextUtils.replaceMsgContent(serviceRecord.getRecording_text()));
        }
        UserServiceOrderVO resultVO = new UserServiceOrderVO();
        BeanUtil.copyProperties(serviceRecord, resultVO);

        if (StringUtils.isNotBlank(recordType) && recordType.equals("cc")) userId = serviceRecord.getCreatedBy();
        List<Sqfw_workorder> workOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceOrderId).and("user_id", "=", userId));
        List<SqfwWorkOrderVO> userVOList = sqfwWorkorderService.getVO(workOrderList);
        if (workOrderList.size() > 0) {
            resultVO.setUserWorkOrder(userVOList.get(0));
        }

        // 根据sqfw_id 和 from_userid 查询相应的工单信息
        List<Sqfw_workorder> userWorkOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                .and("from_user_id", "=", serviceRecord.getCreatedBy()));
        List<SqfwWorkOrderVO> otherUserVOList = sqfwWorkorderService.getVO(userWorkOrderList);
        resultVO.setUserWorkOrderList(otherUserVOList);
        // 使用id和userId查workOrder
        return Result.success(resultVO);
    }

    @At("/deleteServiceOrderLogic")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除录音服务记录")
    @SLog(tag = "删除录音服务记录,工作记录", value = "${args[0]}")
    @ApiFormParams(@ApiFormParam(name = "serviceOrderId", description = "唯一标识", required = true, check = true))
    public Result<Integer> deleteServiceOrderLogic(@Param("serviceOrderId") String serviceOrderId) {
        Integer deleteCount = sqfwServicerecordService.deleteServiceOrderLogic(serviceOrderId);
        if (deleteCount == null || deleteCount == 0) return Result.error("删除失败");
        return Result.success(deleteCount);
    }

    @At("/getServiceOrderByUserId")
    @Ok("json")
    @GET
    @ApiOperation(name = "根据用户id获取所有的服务记录")
    @ApiFormParams(@ApiFormParam(name = "serviceOrderId", description = "唯一标识", required = true, check = true))
    @SLog(tag = "根据用户id获取所有的服务记录")
    public Result<List<ServiceOrderOfUserVO>> getServiceOrderByUserId() {
        String userId = SecurityUtil.getUserId();
        if (StringUtils.isBlank(userId)) Result.error();
        List<Sqfw_servicerecord> list = sqfwServicerecordService.query(Cnd.where("user_id", "=", userId)
                .and("android_file", "is not", null));
        List<ServiceOrderOfUserVO> resultList = list.stream().map(item -> {
            ServiceOrderOfUserVO vo = new ServiceOrderOfUserVO();
            BeanUtil.copyProperties(item, vo);
            return vo;
        }).collect(Collectors.toList());

        return Result.success(resultList);
    }

    @At("/listServiceRecord")
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询通讯服务记录")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_servicerecord.class
    )
    @ApiResponses(
            implementation = Sqfw_servicerecord.class
    )
    @SLog(tag = "分页查询通讯服务记录")
    public Result<?> listServiceRecord(@Param("..") Sqfw_servicerecord bean,
                                       @Param("pageNo") int pageNo,
                                       @Param("pageSize") int pageSize,
                                       @Param("pageOrderName") String pageOrderName,
                                       @Param("pageOrderBy") String pageOrderBy) {

        String userId = SecurityUtil.getUserId();
        List<String> roleList = sysUserService.getRoleList(userId);
        Set<String> roleSet = Sets.newHashSet(roleList);

        Pagination pagination = sqfwServicerecordService.listServiceRecordNew(bean, pageNo, pageSize, roleSet, userId);
        return Result.success(pagination);
    }

    @At("/doUpdateData")
    @Ok("json")
    @GET
    public Result<?> doUpdateData() {
        List<Sqfw_servicerecord> serviceRecordList = sqfwServicerecordService.query(Cnd.where("delflag", "=", false));
        for (Sqfw_servicerecord serviceRecord : serviceRecordList) {
            List<Sqfw_workorder> workOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId()).and("delflag", "=", false));

            List<Sqfw_workorder> otherUserWorkOrderList = Lists.newArrayList();
            Sqfw_workorder workOrderOfServiceRecord = null;
            for (Sqfw_workorder workOrder : workOrderList) {
                if (workOrder.getUser_id().equals(serviceRecord.getCreatedBy())) workOrderOfServiceRecord = workOrder;
                else otherUserWorkOrderList.add(workOrder);
            }

            Set<String> sendUserIdSet = otherUserWorkOrderList.stream().map(Sqfw_workorder::getUser_id).collect(Collectors.toSet());

            List<Sys_user> sendUserList = sysUserService.query(Cnd.where("id", "in", sendUserIdSet));

            List<String> userNameList = Lists.newArrayList();
            List<String> userPhoneList = Lists.newArrayList();
            for (Sys_user sysUser : sendUserList) {
                userNameList.add(sysUser.getUsername());
                userPhoneList.add(sysUser.getLoginname());
            }

            String serviceName = Joiner.on(",").join(userNameList);
            String servicePhone = Joiner.on(",").join(userPhoneList);

            serviceRecord.setService_name(serviceName);
            serviceRecord.setService_phone(servicePhone);

            if (workOrderOfServiceRecord != null) {
                serviceRecord.setFinish_time(workOrderOfServiceRecord.getComplete_time());
                serviceRecord.setFinishStatus(workOrderOfServiceRecord.getWk_status());
            }

            sqfwWorkorderService.update(serviceRecord);
        }

        return Result.success();
    }

    @At("/listAllServiceOrderType")
    @Ok("json")
    @GET
    public Result<List<String>> listAllServiceOrderType(@Param("unitId") String unitId) {
        List<String> list = sqfwServicerecordService.listAllServiceOrderType(unitId);
        return Result.success(list);
    }


    @At("/tesseractOcr")
    @Ok("json")
    @POST
    @ApiOperation(name = "tesseract图片识别")
    @ApiResponses
    @SLog(tag = "tesseract图片识别")
    public String tesseractOcr(@Param("imageFile") File imageFile) {
        /**
         * 设置输出文件的保存的文件目录
         */
        File outputFile = new File(imageFile.getParentFile(), "output");
        StringBuffer strB = new StringBuffer();

        // 设置cmd命令行字符串形式
        List<String> cmd = new ArrayList<String>();
        cmd.add("tesseract");
        cmd.add(imageFile.getName());
        cmd.add(outputFile.getName());
        cmd.add("-l");
        cmd.add("eng");

        try {
            // 启动exe进程
            ProcessBuilder pb = new ProcessBuilder();
            pb.directory(imageFile.getParentFile());
            pb.command(cmd);
            pb.redirectErrorStream(true);
            Process process = pb.start();
            // 等待此进程完成
            int w = process.waitFor();
            if (w == 0) {// 0代表正常退出
                BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile.getAbsolutePath() + ".txt"), "UTF-8"));
                String str;
                while ((str = in.readLine()) != null) {
                    strB.append(str).append(EOL);
                }
                in.close();
            } else {
                String msg;
                switch (w) {
                    case 1:
                        msg = "Errors accessing files. There may be spaces in your image's filename.";
                        break;
                    case 29:
                        msg = "Cannot recognize the image or its selected region.";
                        break;
                    case 31:
                        msg = "Unsupported image format.";
                        break;
                    default:
                        msg = "Errors occurred.";
                }
                logger.error(msg);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        new File(outputFile.getAbsolutePath() + ".txt").delete();
        return strB.toString().replaceAll("\\s*", "");
    }


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "同步Event")
    @ApiResponses
    public Result synEvent(@Param("servicerecordId") String servicerecordId,@Param("fileUrl") String fileUrl,@Param("showFlag") String showFlag ) {
        Sqfw_servicerecord sqfwServicerecord = sqfwServicerecordService.fetch(servicerecordId);
        if(ObjectUtil.isEmpty(sqfwServicerecord)){
            throw new BaseException("servicerecordId错误");
        }
        Sql sql = Sqls.create("UPDATE wx_event SET  show_flag=@showFlag, file_url=@fileUrl WHERE id=@id");
        sql.params().set("id",sqfwServicerecord.getRallyId());
        sql.params().set("fileUrl",fileUrl);
        sql.params().set("showFlag",showFlag);
        dao.execute(sql);
        return Result.success();
    }

    @At("/tesseractOcr1")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据serviceOrderId查询数据")
    @ApiResponses
    @SLog(tag = "根据serviceOrderId查询数据")
    public Result tesseractOcr1() {
        Tesseract instance = new Tesseract();
        instance.setDatapath("C:\\Program Files\\Tesseract-OCR\\tessdata");
        instance.setLanguage("chi_sim");
        File imageFile = new File("D:\\CESHI\\IMG\\testImage.jpg");
        String result = "";
        try {
            result = instance.doOCR(imageFile);
            System.out.println("RESULT==========" + result + "============");
        } catch (TesseractException e) {
            e.printStackTrace();
        }

        return Result.data(result);
    }



    private Cnd createListServiceRecordPermissionCnd(String userId) {

        List<String> roleList = sysUserService.getRoleList(userId);
        Set<String> roleSet = Sets.newHashSet(roleList);

        Cnd cnd = Cnd.NEW();

        boolean superAdminFlag = false;
        boolean adminFlag = false;

        if (roleSet.contains("superadmin") || roleSet.contains("sysadmin")) superAdminFlag = true;
        if (roleSet.contains("admin")) adminFlag = true;

        if (!superAdminFlag && !adminFlag) {
            Sys_user sysUser = sysUserService.fetch(userId);
            SqlExpressionGroup e1 = Cnd.exps("customer_phone", "=", sysUser.getLoginname());
            SqlExpressionGroup e2 = Cnd.exps("service_phone", "like", "%" + sysUser.getLoginname() + "%");
            SqlExpressionGroup e3 = Cnd.exps("copy_phone", "like", "%" + sysUser.getLoginname() + "%");

            cnd.and(e1.or(e2).or(e3));
        }

        if (!superAdminFlag && adminFlag) {
            // 如果只是普通的管理员 首先查出这个公司中所有的员工
            Sys_user sysUser = sysUserService.fetch(userId);
            String unitId = sysUser.getUnitId();
            List<Sys_user> userList = sysUserService.query(Cnd.where("unitid", "=", unitId));
            Set<String> userPhoneSet = userList.stream().map(Sys_user::getLoginname).collect(Collectors.toSet());
            SqlExpressionGroup e = Cnd.exps("customer_phone", "like", "%" + sysUser.getLoginname() + "%");
            for (String userPhone : userPhoneSet) {
                SqlExpressionGroup e1 = Cnd.exps("customer_phone", "like", "%" + userPhone + "%");
                e.or(e1);
            }
            cnd.and(e);
        }

        return cnd;
    }

    @At("/getTask")
    @Ok("json")
    @POST
    @ApiOperation(name = "通过类型获取任务")
    public Result<?> getTask(@Param("type") String type) {

        return sqfwServicerecordService.getTask(type);
    }
}
